<template>
	<view class="uni-container">
		<uni-forms ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item name="s_id" label="规则ID">
				<uni-easyinput v-model="formData.s_id"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name='mer_id' label='机构'>

				<view style="position: relative;">
					<uni-easyinput type="text" v-model="mer_text" @focus="visible = true" @blur="visible = false">
					</uni-easyinput>
					<picker-view class="picker-view" v-if="visible" :indicator-style="indicatorStyle"
						:value="changeVal">
						<picker-view-column>
							<view class="item" v-for="(item,index) in localData" @click="change(item)">
								{{
									item.text
								}}
							</view>
						</picker-view-column>
					</picker-view>

				</view>

				<!-- 		 <uni-data-select
				      collection="mechanism"
				      field="_id as value, name as text"
				      label="机构选择"
					  :page-size="2000"
				      v-model="formData.mer_id"
				      :clear="false"
				    /> -->
			</uni-forms-item>
			<uni-forms-item name="score" label="及格分数">
				<uni-easyinput type="number" v-model="formData.score"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="maxscore" label="满分">
				<uni-easyinput type="number" v-model="formData.maxscore"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="test_times" label="考试时间">
				<uni-easyinput type="number" v-model="formData.test_times"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="type_subject_id" label="科目类型">
				<uni-data-select v-model="formData.type_subject_id" required collection="type-subject" :page-size="100"
					field="s_id as value, name as text">
				</uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="type_drive_id" label="车型">
				<uni-data-select v-model="formData.type_drive_id" ref="drive_udb" collection="type-drive"
					:page-size="500" field="s_id as value, name as text">
				</uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="all_num" label="总题数">
				<uni-easyinput type="number" v-model="formData.all_num"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="radio" label="单选分数">
				<uni-easyinput type="number" v-model="formData.radio"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="multiple" label="多选分数">
				<uni-easyinput type="number" v-model="formData.multiple"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="judge" label="判断分数">
				<uni-easyinput type="number" v-model="formData.judge"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="role_item_ids" label="规则">
				<list-role-item v-if="formData.s_id" :sid="formData.s_id" @changeRoleItem="changeRoleItem">
				</list-role-item>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/test-role.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'test-role';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}
	let formData = {
		"s_id": "",
		"score": 0,
		"maxscore": 0,
		"test_times": 0,
		"type_subject_id": "",
		"type_drive_id": "",
		"all_num": 0,
		"radio": 0,
		"multiple": 0,
		"judge": 0,
		"mer_id": '',
		"role_item_ids": []
	}
	export default {
		data() {

			return {
				changeVal: [],
				visible: false,
				indicatorStyle: `height: 50px;`,
				mer_text: '',

				formData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				},
				copyList: [],
				searchData: [],
				localData: []
			}
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
				
			}
		},
		watch: {
			"mer_text"(newVal) {
				this.fillterMech(newVal)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			change(e) {
				this.formData.mer_id = e._id
				this.mer_text = e.text
			},
			async getAllMerList() {
				let db = uniCloud.database()
				const responseTotal = await db.collection('mechanism').count()
				const size = responseTotal.result.total
				if (size > 0) {
					let total = size
					let processSize = 0
					let position = 1
					let allData = []
					while (processSize < total) {
						const responseData = await db.collection('mechanism')
							.field('_id as value,name as text')
							.skip(processSize).limit(500).get()
						if (responseData.result.data.length > 0) {
							responseData.result.data.forEach((e) => {
								e.indexId = position++
								allData.push(e)
							})
						}
						processSize += responseData.result.data.length
					}

					this.copyList = allData
					let temp = []
					for (let s of this.copyList) {
						temp.push(s)
						if(s._id === this.formData.mer_id){
							this.mer_text = s.text
						}
					}

					this.localData = temp
				}
			},
			fillterMech(e) {
				console.log('e', e)
				if (e == '') {
					this.localData = this.copyList
					return
				}
				let searchData = []
				for (let row of this.copyList) {
					if (row.text.indexOf(e) != -1) {
						searchData.push(row)
					}
				}
				if (searchData.length > 0) {
					this.localData = searchData
				}
			},

			changeRoleItem(e) {
				this.formData.role_item_ids = e
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				value.sid = Number(value.s_id)
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					"s_id,score,mer_id,maxscore,test_times,type_subject_id,type_drive_id,all_num,radio,multiple,judge,role_item_ids"
				).get().then((res) => {
					const data = res.result.data[0]
					if (data) {
						this.formData = data
						this.getAllMerList()
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>
<style>
	.picker-view {
		width: 700rpx;
		height: 600rpx;
		margin-top: 20rpx;
		background-color: #ababab;
		color: #000;
		position: absolute;
		z-index: 9999;
		border-radius: 12rpx;

	}

	.item {
		line-height: 100rpx;
		text-align: center;
		background-color: #c3c3c3;
	}
</style>